package net.sk.china.platform.manager;

import cn.hutool.core.util.ObjectUtil;
import net.sk.china.platform.response.system.LoginSystemResponse;
import net.sk.china.platform.service.impl.system.AdminDetailServiceImpl;
import net.sk.china.common.exception.TalkException;
import net.sk.china.common.utils.TalkUtil;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * 自定义验证
 * +----------------------------------------------------------------------
 * | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2018-2024 聊来All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * +----------------------------------------------------------------------
 * | @Author: 聊来 <18970881148@qq.com>
 * +----------------------------------------------------------------------
 * | DateTime: 2024/6/2 15:21
 * +----------------------------------------------------------------------
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    private AdminDetailServiceImpl adminDetailsService;

    public CustomAuthenticationProvider(AdminDetailServiceImpl adminDetailsService) {
        this.adminDetailsService = adminDetailsService;
    }

//    private final UserDetailServiceImpl userDetailsService = new UserDetailServiceImpl();

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getPrincipal().toString();
        String password = authentication.getCredentials().toString();


        //以下自定义方法，判断是否登录成功
        LoginSystemResponse userDetails = (LoginSystemResponse) adminDetailsService.loadUserByUsername(name);
        if (ObjectUtil.isNull(userDetails)) {
            throw new TalkException("用户名不存在");
        }
        // base64加密获取真正密码
        String encryptPassword = TalkUtil.encryptPassword(password, name);
        if (!userDetails.getUser().getPwd().equals(encryptPassword)) {
            throw new TalkException("账号或者密码不正确");
        }
        return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        //确保authentication能转成该类
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}